package com.example.demo.controller;

import com.example.demo.pojo.Product;
import com.example.demo.pojo.Response;
import com.example.demo.service.ProductService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/product")
@Tag(name = "商品管理", description = "商品管理相关接口")
public class ProductController {
    @Autowired
    ProductService productService;

    @Operation(summary = "添加商品")
    @PostMapping(value = "/addProduct")
    @ApiResponse(responseCode = "200", description = "商品添加成功", content = @Content(mediaType = "application/json"))
    public ResponseEntity<Response<Product>> addProduct(@Parameter(description = "要添加的商品") @RequestBody Product product) {

        Response<Product> response = new Response<>();
        try {
            Product newProduct = productService.addProduct(product);
            response.setCode(200);
            response.setMessage("商品添加成功");
            response.setProduct(newProduct);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage("服务器错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @Operation(summary = "添加商品图片")
    @PutMapping("/add/product_picture")
    @ApiResponse(responseCode = "200", description = "商品图片添加成功", content = @Content(mediaType = "multipart/form-data"))
    public ResponseEntity<Response<Product>> addProductPicture(@Parameter(description = "要添加的商品") @RequestParam("product_id") Integer product_id,
                                                               @Parameter(description = "要添加的商品图片") @RequestParam("product_picture") MultipartFile product_picture) {
        Response<Product> response = new Response<>();
        try {
            FileController fileController = new FileController();

            Product product = productService.findById(product_id);
            if (product == null) {
                response.setCode(404);
                response.setMessage("商品未找到");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }

            if (product.getProduct_picture() != null && !product.getProduct_picture().isEmpty()) {
                System.out.println(product.getProduct_picture());
                String avatarPath = product.getProduct_picture();
                if (avatarPath.startsWith("/")) {
                    avatarPath = avatarPath.substring(1);
                }
                fileController.deleteFile(avatarPath);
            }

            ResponseEntity<String> url = fileController.uploadFile(product_picture);
            Product newproduct = productService.updateProductPicture(product_id, url.getBody());

            response.setCode(200);
            response.setMessage("商品图片添加成功");
            response.setProduct(newproduct);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage("服务器错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }


    @Operation(summary = "查找所有商品")
    @GetMapping("/find-all")//查找所有商品
    @ApiResponse(responseCode = "200", description = "商品查找成功", content = @Content(mediaType = "application/json"))
    public ResponseEntity<Response<Product>> findAll() {
        Response<Product> response = new Response<>();

        try {
            List<Product> productList = productService.findAllProduct();
            if (productList.isEmpty()) {
                response.setCode(404);
                response.setMessage("商品列表为空");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
            response.setCode(200);
            response.setMessage("查找成功");
            response.setList(productList);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage("服务器错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @Operation(summary = "查找商品byID或名称")
    @GetMapping("/find-byIdOrName")
    @ApiResponse(responseCode = "200", description = "商品查找成功", content = @Content(mediaType = "application/json"))
    public ResponseEntity<Response<Product>> findByIdOrName(@Parameter(description = "商品ID或名称") @RequestParam("product_id_or_name") String product_id_or_name) {
        Response<Product> response = new Response<>();
        try {
            List<Product> productList = productService.findByIdOrName(product_id_or_name);
            if (productList.isEmpty()) {
                response.setCode(404);
                response.setMessage("商品列表为空");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
            response.setCode(200);
            response.setMessage("查找成功");
            response.setList(productList);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage("服务器错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @Operation(summary = "查找商品by类别")
    @GetMapping("/find-byclass")//查看商品列表
    @ApiResponse(responseCode = "200", description = "商品查找成功", content = @Content(mediaType = "application/json"))
    public ResponseEntity<Response<Product>> findByClass(@Parameter(description = "商品类别") @RequestParam("product_class") String product_class) {
        System.out.println(product_class);
        Response<Product> response = new Response<>();
        try {
            List<Product> productList = productService.findByClass(product_class);

            response.setCode(200);
            response.setMessage("查找成功");
            response.setList(productList);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage("服务器错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @Operation(summary = "查找商品byid")
    @GetMapping("/find-byid")
    @ApiResponse(responseCode = "200", description = "商品查找成功", content = @Content(mediaType = "application/json"))
    public ResponseEntity<Response<Product>> findById(@Parameter(description = "商品ID") @RequestParam("product_id") Integer product_id) {
        Response<Product> response = new Response<>();
        try {
            Product product = productService.findById(product_id);
            if (product == null) {
                response.setCode(404);
                response.setMessage("商品不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
            response.setCode(200);
            response.setMessage("查找成功");
            response.setProduct(product);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage("服务器错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @Operation(summary = "模糊搜索")
    @GetMapping("/search")
    @ApiResponse(responseCode = "200", description = "商品查找成功", content = @Content(mediaType = "application/json"))
    public ResponseEntity<Response<Product>> search(@Parameter(description = "商品名称") @RequestParam("product_name") String product_name) {
        Response<Product> response = new Response<>();
        try {
            List<Product> productList = productService.findByName(product_name);

            response.setCode(200);
            response.setMessage("搜索成功");
            response.setList(productList);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage("服务器错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @Operation(summary = "删除商品")
    @DeleteMapping("/delete/product_id")
    @ApiResponse(responseCode = "200", description = "商品删除成功", content = @Content(mediaType = "application/json"))
    public ResponseEntity<Response<Product>> deleteProduct(@Parameter(description = "商品ID") @RequestParam("product_id") Integer product_id) {
        Response<Product> response = new Response<>();
        try {
            Product product = productService.findById(product_id);
            if (product == null) {
                response.setCode(404);
                response.setMessage("商品不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
            FileController fileController = new FileController();
            if (product.getProduct_picture() != null && !product.getProduct_picture().isEmpty()) {
                System.out.println(product.getProduct_picture());
                String avatarPath = product.getProduct_picture();
                if (avatarPath.startsWith("/")) {
                    avatarPath = avatarPath.substring(1);
                }
                fileController.deleteFile(avatarPath);
            }

            productService.deleteProduct(product_id);
            response.setCode(200);
            response.setMessage("删除成功");
            response.setProduct(product);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage("服务器错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);

        }
    }

    @Operation(summary = "修改商品")
    @PutMapping("/update/productinfo")
    @ApiResponse(responseCode = "200", description = "商品修改成功", content = @Content(mediaType = "application/json"))
    public ResponseEntity<Response<Product>> updateProduct(@Parameter(description = "商品ID") @RequestParam("product_id") Integer product_id,
                                                           @Parameter(description = "商品名称") @RequestParam("product_name") String product_name,
                                                           @Parameter(description = "商品价格") @RequestParam("product_price") float product_price,
                                                           @Parameter(description = "商品库存") @RequestParam("product_stock") Integer product_stock,
                                                           @Parameter(description = "商品类别") @RequestParam("product_class") String product_class) {

        Response<Product> response = new Response<>();
        Product product = productService.findById(product_id);
        try {
            if (product == null) {
                response.setCode(404);
                response.setMessage("商品不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }

            Product newproduct = productService.ModifyProduct(product_id, product_name, product_price, product_stock, product_class);
            response.setCode(200);
            response.setMessage("修改成功");
            response.setProduct(newproduct);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.setCode(500);
            response.setMessage("服务器错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
}
